import {Component} from 'react';
import {connect} from 'react-redux';
import axios from 'axios';
import * as Notification from 'modules/notification/actions';
import Session from 'modules/auth/session';
import styled from "styled-components";
import {Button, Empty, Input, Modal, PageHeader, Table} from 'antd';

const ButtonGroup = Button.Group;
const Outer = styled.div`
  border:1px solid #ececec;
  margin:20px;
   box-shadow: 3px 3px 6px rgba(0,0,0,0.1), 3px 3px 6px rgba(0,0,0,0.2);
`;


const Conten = styled.div`
  margin: 20px;
  box-sizing:border-box;
`;
const ContenTiTle = styled.div`
padding:1px;
 background:#f1f1f1;
`;
const ContenList = styled.div`
  display:flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
`;
const CenterName = styled.div`
  width:180px;
  font-size:14px;
  color:#000;
  text-align:right;
  padding-right:15px;
`;
const CenterInputOuter = styled.div`
  width:400px;
  font-size:14px;
  color:#000;
`;


class Collection extends Component {
    state = {
        search: '',
        document: {
            action: '',
            visible: false,
            dimmed: false
        },
        confirm: {
            visible: false,
            imsi: ''
        },
        view: {
            visible: false,
            disableOnClickOutside: false,
            imsi: ''
        },
        visible: false,
        modelTitle: '新增会话规则参数',
        configData: {},
        selectedRowKeys: [], // Check here to configure the default column
        loading: false,
        SessionRulesData: [],
        SessionRuleId: '',
        SessionAmbrUI: '',
        SessionAmbrDI: '',

    };


    onSelectChange = selectedRowKeys => {
        this.setState({selectedRowKeys});
    };


    componentWillMount() {

        const {dispatch} = this.props;
        let $this = this;
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf};
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/smf',
            params: {},
            // data
        }).then(res => {
            var configData = res.data[0].config;
            $this.setState({
                    configData: res.data[0],
                    SessionRulesData: configData.SessionRulesData || []
                }
            )

        })
    }

    getSData = () => {
        const {dispatch} = this.props;
        let $this = this;
        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf};
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "get",
            url: '/smf',
            params: {},
            // data
        }).then(res => {
            var configData = res.data[0].config;
            $this.setState({
                    configData: res.data[0],
                    SessionRulesData: configData.SessionRulesData || []

                }
            );

            dispatch(Notification.success({
                title: '提示',
                message: `会话规则参数列表刷新成功！`
            }));
        })
    };

    handleOk = e => {
        let $this = this;

        let editorBol = false;
        if (this.state.modelTitle == '修改会话规则参数') {
            editorBol = true
        }
        const {dispatch} = this.props;
        let sendData = JSON.parse(JSON.stringify(this.state.configData));
        sendData.config.SessionRulesData = sendData.config.SessionRulesData || [];
        let sendLine = {};
        sendLine.SessionAmbrUI = this.state.SessionAmbrUI;
        sendLine.SessionAmbrDI = this.state.SessionAmbrDI;

        if (sendLine.SessionAmbrUI == '' ||
            sendLine.SessionAmbrDI == ''
        ) {
            dispatch(Notification.error({
                title: '提示', autoDismiss: 4,
                message: `会话规则参数的值不能为空！`
            }));
            return false
        }


        if (editorBol) {

            sendData.config.SessionRulesData.forEach(a => {
                if (a.SessionRuleId == $this.state.SessionRuleId) {
                    a.SessionAmbrUI = sendLine.SessionAmbrUI;
                    a.SessionAmbrDI = sendLine.SessionAmbrDI
                }
            })
        } else {
            sendLine.key = parseInt(Math.random() * 10000000000);
            sendLine.SessionRuleId = sendData.config.SessionRulesData.length == 0 ? 1 : (sendData.config.SessionRulesData[sendData.config.SessionRulesData.length - 1].SessionRuleId + 1);
            sendData.config.SessionRulesData.push(sendLine)
        }

        const sessionData = new Session();
        const csrf = ((sessionData || {}).session || {}).csrfToken;
        const authToken = ((sessionData || {}).session || {}).authToken;
        let headers = {'X-CSRF-TOKEN': csrf};
        if (authToken) {
            headers['Authorization'] = "Bearer " + authToken
        }

        axios({
            baseURL: '/api/db',
            headers: headers,
            method: "PATCH",
            url: '/smf/' + sendData._id,
            data: sendData,
            //
        }).then(res => {
            this.handleCancel();
            var configData = res.data.config;
            $this.setState({
                    configData: res.data,
                    SessionRulesData: configData.SessionRulesData || []
                }
            );
            dispatch(Notification.success({
                title: '提示',
                message: `会话规则参数配置成功！`
            }));
        })
    };

    showModal = () => {
        this.setState({
            visible: true,
        });
    };


    handleCancel = e => {
        this.setState({
            visible: false,
        });
    };


    _handleChange(e) {
        // 获取 input 元素上的value
        let name = e.target.name;
        let value = e.target.value;
        this.setState({
            [name]: value
        })
    };

    addRow = () => {
        this.setState({
            modelTitle: '新增会话规则参数',
            SessionAmbrUI: '',
            SessionAmbrDI: ''
        });
        this.showModal()
    };

    editRow = (row, e) => {

        this.setState({
            modelTitle: '修改会话规则参数',
            SessionAmbrUI: row.SessionAmbrUI,
            SessionRuleId: row.SessionRuleId,
            SessionAmbrDI: row.SessionAmbrDI
        });
        this.showModal()
    };

    render() {
        let $this = this;
        const {loading, selectedRowKeys} = this.state;
        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };
        const hasSelected = selectedRowKeys.length > 0;


        const columns = [
            {
                title: '操作',
                dataIndex: '',
                key: 'y',
                width: 240,
                render: (text, record) => {
                    return (
                        <div>

                            <ButtonGroup>

                                <Button type="primary" onClick={(e) => this.editRow(record, e)}>修改</Button>
                                <Button type="danger" onClick={(e) => this.delRow(record, e)}>删除</Button>
                            </ButtonGroup>
                        </div>
                    )
                },
            },
            {
                title: 'SessionRuleId',
                dataIndex: 'SessionRuleId',
            },
            {
                title: 'SessionAmbrDI',
                dataIndex: 'SessionAmbrDI',
            },
            {
                title: 'SessionAmbrUI',
                dataIndex: 'SessionAmbrUI',
            },
        ];


        return (
            <div>
                <PageHeader
                    style={{
                        border: '1px solid rgb(235, 237, 240)',
                    }}
                    title="会话规则参数列表"
                />
                <Outer>
                    <Conten>
                        <div>
                            <div style={{marginBottom: 16}}>
                                <Button type="success" onClick={this.addRow}>
                                    新增
                                </Button>
                                <span>&nbsp;&nbsp;</span>
                                <Button type="primary" onClick={this.getSData}>
                                    刷新
                                </Button>
                                <span>
                                    &nbsp;&nbsp;共{this.state.SessionRulesData.length}条数据&nbsp;&nbsp;&nbsp;&nbsp;
                                </span>
                                <span
                                    style={{marginLeft: 8}}>{hasSelected ? `Selected ${selectedRowKeys.length} items` : ''} </span>
                            </div>
                            <Table
                                locale={
                                    {
                                        emptyText: () => {
                                            return (
                                                <Empty
                                                    description={
                                                        <span>暂无数据</span>
                                                    }
                                                />
                                            )
                                        }
                                    }
                                }
                                columns={columns} dataSource={this.state.SessionRulesData}/>
                        </div>
                    </Conten>
                </Outer>


                <Modal
                    title={this.state.modelTitle}
                    visible={this.state.visible}
                    onOk={this.handleOk}
                    onCancel={this.handleCancel}
                    okText="确认"
                    width={800}
                    cancelText="取消"
                >
                    <ContenTiTle>
                        <ContenList>
                            <CenterName><strong>参数名</strong></CenterName>
                            <CenterInputOuter>
                                <strong>值</strong>
                            </CenterInputOuter>
                        </ContenList>
                    </ContenTiTle>

                    <ContenList><CenterName>SessionAmbrDI</CenterName>
                        <CenterInputOuter>
                            <Input
                                name={'SessionAmbrDI'}
                                type={"number"}
                                onChange={(e) => this._handleChange(e)}
                                value={this.state.SessionAmbrDI}
                                title={'请输入SessionAmbrDI，根据实际提供的填写'}
                                placeholder={'请输入SessionAmbrDI，根据实际提供的填写'}/>
                        </CenterInputOuter>
                    </ContenList>

                    <ContenList>
                        <CenterName>SessionAmbrUI</CenterName>
                        <CenterInputOuter>
                            <Input
                                value={this.state.SessionAmbrUI}
                                name={'SessionAmbrUI'}
                                onChange={(e) => this._handleChange(e)}
                                placeholder={'请输入SessionAmbrUI，根据实际情况进行填写'}
                                title={'请输入SessionAmbrUI，根据实际情况进行填写'}
                            /></CenterInputOuter>
                    </ContenList>
                </Modal>
            </div>
        )
    }

    delRow = (row, e) => {
        const {dispatch} = this.props;

        var $this = this;
        Modal.confirm({
            title: '确定要删除 SessionRuleId 为 ' + row.SessionRuleId + ' 的数据么？',
            content: '删除后无法找回',
            okText: '确认',
            cancelText: '取消',
            onOk: function () {
                let sendData = JSON.parse(JSON.stringify($this.state.configData));
                let newPData = [];
                sendData.config.SessionRulesData.forEach(a => {
                    if (a.SessionRuleId != row.SessionRuleId) {
                        newPData.push(a)
                    }
                });
                sendData.config.SessionRulesData = newPData;

                const sessionData = new Session();
                const csrf = ((sessionData || {}).session || {}).csrfToken;
                const authToken = ((sessionData || {}).session || {}).authToken;
                let headers = {'X-CSRF-TOKEN': csrf};
                if (authToken) {
                    headers['Authorization'] = "Bearer " + authToken
                }

                axios({
                    baseURL: '/api/db',
                    headers: headers,
                    method: "PATCH",
                    url: '/smf/' + sendData._id,
                    data: sendData,
                    //
                }).then(res => {
                    $this.handleCancel();
                    var configData = res.data.config;
                    $this.setState({
                            configData: res.data,
                            SessionRulesData: configData.SessionRulesData || []
                        }
                    );
                    dispatch(Notification.success({
                        title: '提示',
                        message: `会话规则参数删除成功！`
                    }));
                })
            }
        });
    }
}

Collection = connect(
    (state) => ({})
)(Collection);

export default Collection;